import 'dart:async';

import 'package:get/get.dart';

class RemainingTimerController extends GetxController {
  final int remainingSeconds;
  final int timeoutSeconds;
  final Function()? callback;

  Timer? _timer;
  int _remainingSeconds = 1;
  final time = '00:00:00'.obs;

  RemainingTimerController(
      {required this.remainingSeconds,
      required this.timeoutSeconds,
      required this.callback});

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    _startTimer();
    super.onReady();
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }

  _startTimer() {
    const duration = Duration(seconds: 1);
    _remainingSeconds = remainingSeconds;
    _timer = Timer.periodic(duration, (Timer timer) {
      if (_remainingSeconds == 0) {
        _remainingSeconds = timeoutSeconds;
        if (callback != null) {
          callback!();
        }
      } else {
        int hours = _remainingSeconds ~/ 3600;
        int minutes = _remainingSeconds ~/ 60;
        int seconds = (_remainingSeconds % 60);
        time.value =
            '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
        _remainingSeconds--;
        //update();
      }
    });
  }
}
